<?php
// +---------------------------------------------------------------------------+
// | This file is part of the KnowledgebasePublisher package                   |
// | KnowledgebasePublisher - web based knowledgebase publisher tool           |
// |                                                                           |
// | Author:  Evgeny Leontev <eleontev@gmail.com>                              |
// | Copyright (c) 2005 Evgeny Leontev                                         |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code.                          |
// +---------------------------------------------------------------------------+

class KBClientView extends BaseView
{	

	var $working_dir;
	var $template_dir;
	var $template_view_dir;
	var $template;
	var $errors = array();
	var $form_data = array();
	
	var $msg = array();
	var $controller;
	var $css = array();
	
	var $meta_title;
	var $meta_keywords;
	var $meta_description;
	
	var $category_key;
	var $category_id;
	var $entry_key;
	var $entry_id;
	var $view_key;
	
	var $home_link = false; 			// use home link n navigation as link 
	var $category_nav_generate = true; 	// generate or not categories in navigation line
	var $settings = array();
	
	var $nav_delim = '»';
	var $display_categories = true;		// display form with categories and other staff with categories
	                                    // later we count categories and set var in KBClientView::getTop
	
	var $top_parent_id = 0;
	var $extra_breadcrumbs = array();
	var $page_template = 'page.html';
	
	// to manipulate, share, mix templates
	var $own_format = 'all';
	var $default_format = 'default';
	//var $view_default_template = 'default';
	//var $view_template = array('default'=>'all',
	//                           'no_header'=>'top.html');
	
	
	//function KBClientView(&$controller) {
	function KBClientView() {

		$reg = &Registry::instance();
		$this->conf = &$reg->getEntry('conf');
		$this->controller = &$reg->getEntry('controller');
		$this->encoding = $this->conf['lang']['meta_charset'];
		
		//$this->setTemplateDir($this->controller->getSetting('view_format'), 
		//                      $this->controller->getSetting('view_template'));
							  
		$this->setTemplateDir($this->controller->view_format_value, 'default');
		
		$this->setCommonStyleCss(1);
		$this->setStyleCss($this->controller->view_format_value,
		                   $this->controller->getSetting('view_template'),
						   $this->controller->getSetting('view_style'));
						   
		$this->setMsg();
		$this->setUrlVars();
	}
	
	
	function setUrlVars() {
		//$this->category_key = &$this->controller->category_key;
		$this->category_id = $this->controller->category_id;
		//$this->entry_key = &$this->controller->entry_key;
		$this->entry_id = $this->controller->entry_id;
		//$this->view_key = &$this->controller->view_key;
		$this->view_id = $this->controller->view_id;
		//$this->msg_key = &$this->controller->msg_key;
		$this->msg_id = $this->controller->msg_id;
	}
	
	
	function setTemplateDir($format, $skin) {

		if($this->own_format == 'none') {
			$format = $this->default_format;
		} elseif($this->own_format != 'all') {
			$format = (in_array($this->view_id, $this->own_format)) ? $format : $this->defalt_format;
		}
		
		$this->template_dir = $this->getTemplateDir($format, $skin);
	}	
	
	
	function getTemplateDir($format, $skin) {
		return $this->controller->skin_dir . 'view_' . $format . '/' . $skin . '/';
	}
	
	
	function getTemplate($template) {
		
		//$format = $this->controller->getSetting('view_format');
		$skin = $this->controller->getSetting('view_template');
		$template_dir = $this->template_dir;
		
		if(isset($this->view_template[$skin])) {
			$t = $this->view_template[$skin];
			if(stripos($t, $template)  !== false) {
				$template_dir = $this->getTemplateDir($this->controller->view_format_value,
		                                              $skin);
			}
		}
		
		return $template_dir . $template;
	}
	
	
	function setStyleCss($format, $skin, $style) {
		$this->css['style_css'] = $this->controller->skin_path . 'view_' . $format . '/' . $skin . '/' . $style . '.css';
	}
	
	
	function setCommonStyleCss($size) {
		$this->css['fontsize_css'] = $this->controller->skin_path . 'fontsize_normal.css';
		$this->css['common_css'] = $this->controller->skin_path . 'common.css';
		$this->css['common_ie_css'] = $this->controller->skin_path . 'common_ie.css';
	}
	
	
	function getMsgFile($file, $module = true) {
		require_once 'core/app/AppMsg.php';
		return ($module) ? AppMsg::getModuleMsgFile($module, $file) 
		                 : AppMsg::getCommonMsgFile($file);
	}
	
	function setMsg() {
		$file = $this->getMsgFile('client_msg.ini', 'knowledgebase');
		$this->msg = AppMsg::parseMsgs($file, false, false);
	}
	
	function addMsg($file, $module) {
		$file = $this->getMsgFile($file, $module);
		$this->msg = array_merge($this->msg, AppMsg::parseMsgs($file, false, false));
	}
	
	function getFormatedDate($timestamp, $format = null) {
		$format = ($format) ? $format : $this->conf['lang']['date_format'];
		return $this->_getFormatedDate($timestamp, $format);
	}	
	
	
	function getActionMsg($format = 'success', $msg_id = false, $strip = false) {
		
		$this->msg_id = ($msg_id) ? $msg_id : $this->msg_id;
		
		if($this->msg_id) {
			require_once 'eleontev/HTML/BoxMsg.php';
			
			$file = $this->getMsgFile('client_after_action_msg.ini', 'knowledgebase');
			$msgs = AppMsg::parseMsgs($file, $this->msg_id, true);
			
			if($msgs) {
				if($strip) { $msgs = parent::stripVars($msgs, array(), $strip); }
				return BoxMsg::factory($format, $msgs);
			}
		}
	}
	
	
	// true if commentable
	function isCommentable($manager, $var = true) {
		return (bool) ($manager->getSetting('allow_comments') && $var);
	}
	
	
	// true if ratingable
	function isRatingable($manager, $var = true) {
		return (bool) ($manager->getSetting('allow_rating') && $var);
	}	

	
	function getCaptchaSrc() {
		return $this->controller->kb_path . 'captcha.php';
	}
	
	
	function useCaptcha($manager, $section) {
		
		$ret = false;
		$captcha_val = $section . '_captcha';
		$captcha_set = $manager->getSetting($captcha_val);
		
		if($captcha_set == 'yes') {
			$ret = true;
		} elseif($captcha_set == 'yes_no_reg' && !$manager->is_registered) {
			$ret = true;
		}
		
		return $ret;
	}
	
	
	function pageByPage($limit, $sql, $per_page = false) {
		
		require_once 'eleontev/PageByPage.php';

		$bp = new PageByPage($limit);	
		$bp->action_page = $this->_getLink($this->view_id, $this->category_id, $this->entry_id);
		
		$bp->setMsg($this->msg['page_msg'], $this->msg['record_msg'], $this->msg['record_from_msg']);
		$bp->countAll($sql); 
		
		return $bp;
	}	
	
	
	function setErrors($errors) {
		$this->errors = $errors;
	}
	
	
	function getErrors() {
		require_once 'core/app/AppMsg.php';
		return AppMsg::errorBox($this->errors, $module = false);
	}
	
	
	// use it when wronng form submission	
	function setFormData(&$arr) {
		$this->form_data = &$arr;
	}
	
	
	function &stripVars($values, $html = true, $to_display = 'display') {
		return parent::stripVars($values, array('body'), $to_display);
	}
	
	
	// to popularte in form after wronng form submission
	function getFormData() {
		$this->form_data['required_sign'] = '<span class="requiredSign">*</span>';		
		return $this->form_data;
	}
	
	
	function _getItemImg($registered, $var, $category = false, $ext = false) {
		
		//if($var && !$registered && $this->isExtra('private')) {
		if($var && !$registered) {
			$tag = '<img src="%simages/icons/lock1.gif" alt="private" width="14" height="16" title="%s" />';
			$tag = sprintf($tag, $this->controller->client_path, $this->msg['login_to_view_msg']);
		
		} elseif($category === 'file') {
			$_file = sprintf('%sclient/images/filetypes/%s.png', $this->controller->kb_dir, $ext);
			$file = sprintf('%simages/filetypes/%s.png', $this->controller->client_path, $ext);
			if(!file_exists($_file)) {
				$file = sprintf('%simages/filetypes/%s.png', $this->controller->client_path, 'file');
			}
			
			$tag = sprintf('<img src="%s" alt="file" width="18" height="16" />', $file);		
			
		} else {
			$tag = ($category) ? '<img src="%simages/icons/folder.gif" alt="folder" width="15" height="12" />'
			                   : '<img src="%simages/icons/article.gif" alt="document" width="11" height="14" />';
			$tag = sprintf($tag, $this->controller->client_path);
		}

		return $tag;
	}
	
	
	function _getRating($var) {
		if($var) {
			$tag = '<img src="%simages/rating/rate_line_8px/rate_%s.gif" alt="rating" />';
			$rate = sprintf($tag, $this->controller->client_path, round($var));
		} else {
			$rate = $this->msg['not_rated_msg']; 
		}
		
		return $rate;
	}
	
	
	function _getRateRange() {
		$file = $this->getMsgFile('rating_range_msg.ini', 'knowledgebase');
		return AppMsg::parseMsgs($file);
	}
	
	
	function getRowClass() {
		static $i = 1;
		return ($i++ & 1) ? 'trDarker' : 'trLighter'; // rows colors
	}
		
	
	function _getLink($view = false, $category_id = false, $entry_id = false, $msg_key = false) {
		return $this->controller->getLink($view, $category_id, $entry_id, $msg_key); 
	}
	
	
	function getRssHeadLinks($manager) {
		
		$rss = false;
		$rss_setting = $manager->getSetting('rss_generate');
		$rss_head = '<link rel="alternate" type="application/rss+xml" title="%s" href="%s" />';
		$rss_file = $this->controller->kb_path . 'rss.php';
		$rss_title = $manager->getSetting('rss_title');
		
		// one common rss
		if($rss_setting == 'one') {
			$rss = sprintf($rss_head, $rss_title, $rss_file);
		
		// all top categories
		} elseif($rss_setting == 'top') {
			
			foreach($this->stripVars($manager->categories) as $category_id => $v) {
				if($v['private'] == 0 && $v['parent_id'] == 0) {
					$categories[$category_id] = $v;
				}
			}
			
			// common one
			$rss = array();
			$rss[] = sprintf($rss_head, $rss_title, $rss_file);
			
			// category page
			if($this->category_id) {
				if(isset($categories[$this->category_id])) {
					$category_id = TreeHelperUtil::getTopParent($manager->categories, $this->category_id);
					$_rss_file = $rss_file . '?c=' . $category_id;
					//$title = sprintf('%s (%s)', $rss_title, $categories[$category_id]['name']);
					$title = $categories[$category_id]['name'];
					$rss[] = sprintf($rss_head, $title, $_rss_file);
				}
			
			// index page
			} else {
				foreach($categories as $category_id => $v) {
					$_rss[$category_id] = $v['sort_order'];
				}
				
				asort($_rss);
				foreach($_rss as $category_id => $v) {
					$_rss_file = $rss_file . '?c=' . $category_id;
					//$title = sprintf('%s (%s)', $rss_title, $categories[$category_id]['name']);
					$title = $categories[$category_id]['name'];
					$rss[] = sprintf($rss_head, $title, $_rss_file);
				}	
			}
				
			$rss = implode("\n\t", $rss);
		}
		
		return $rss;
	}
	
	
	function &getTop(&$manager, $article_name = false, $parse_form = true) {
		
		$tpl = &new tplTemplatez($this->getTemplate('top.html'));
		
		// need to print msg if any
		$tpl->tplAssign('msg', $this->getActionMsg('error'));
		
		//header
		$tpl->tplAssign('header_title', $manager->getSetting('header_title'));
		$tpl->tplAssign('header_title_link', $this->_getLink());
		
		
		/*
		// one category - test values
		$simple_arr = array();
		$simple_arr[1]['id'] = 1;
        $simple_arr[1]['parent_id'] = 0;
        $simple_arr[1]['name'] = 'default';
        $simple_arr[1]['sort_order'] = 1;
		*/
		//echo "<pre>"; print_r($simple_arr); echo "</pre>";
		
		/*
		//decide dispaly category staff or not
		if(count($simple_arr) == 1) {
			reset($simple_arr);
			if(strtolower($simple_arr[key($simple_arr)]['name']) == 'default') { 
				$this->display_categories = false;
			}
		}
		*/
		if ($manager->is_registered) {
            $tpl->tplAssign('menu_position', '<a class="leftmenu" href="' . APP_HOME_PATH . '"  target="blank">' . $this->msg['enter_admin_msg']. '</a>');
        }
		
		$tpl->tplAssign('navigation', $this->_getFormatedNavigation($manager->categories, $article_name));
		
		// auth info
		$this->parseLogin($tpl, $manager);
		
		
		// FORM
		if($parse_form) {
			
			if($manager->getSetting('allow_contact')) {
				$tpl->tplSetNeededGlobal('contact');
				$tpl->tplAssign('contact_link', $this->_getLink('contact', $this->category_id));
			}			
			
			if($manager->getSetting('show_glossary_link')) {
				if($manager->isGlossary()) {
					$tpl->tplSetNeededGlobal('glossary');
					$tpl->tplAssign('glossary_link', $this->_getLink('glossary'));
					$tpl->tplAssign('glossary_delim', ($manager->getSetting('allow_contact')) ? '|' : '');
				}		
			}
			
			if($manager->getSetting('show_file_link') && $manager->isExtra('file')) {
				$tpl->tplSetNeededGlobal('file');
				$tpl->tplAssign('file_link', $this->_getLink('files'));
			}			
			

			// categories ? 
			// probably in some cases we should not dispaly categories if 1 for example
			if($this->display_categories) {
				$tpl->tplAssign('category_select', $this->_getCategorySelect($manager));
			}

            $tpl->tplAssign('left_side', $this->_getCategoryTree($manager));


			//<input type="hidden" name="View" value="search">
			$search_str = (isset($_GET['q'])) ? sprintf('?q=%s', $_GET['q']) : '';
			if($this->view_id == 'files') {
			
				if(!$this->controller->mod_rewrite) {
					$ar = array($this->view_key => 'files', $this->msg_key => 'search');
					$tpl->tplAssign('hidden_search', http_build_hidden($ar));
					
					$ar = array($this->view_key => 'files');
					$tpl->tplAssign('hidden_category', http_build_hidden($ar));					
				}				
			
				$tpl->tplAssign('form_search_action', $this->_getLink('files', $this->category_id, '', 'search'));
				$tpl->tplAssign('form_category_action', $this->_getLink('files', $this->category_id));
				$tpl->tplAssign('advanced_search_link', $this->_getLink('files', $this->category_id, '', 'search') . $search_str);
			
			} else {
			
				if(!$this->controller->mod_rewrite) {
					$ar = array($this->controller->getRequestKey('view') => 'search');
					$tpl->tplAssign('hidden_search', http_build_hidden($ar));
				}				
			
				$tpl->tplAssign('form_category_action', $this->_getLink());
				$tpl->tplAssign('form_search_action', $this->_getLink('search', $this->category_id));
				$tpl->tplAssign('advanced_search_link', $this->_getLink('search', $this->category_id) . $search_str);
			}

			$tpl->tplSetNeeded('/form');
		}
		
		$tpl->tplAssign('kb_path', $this->controller->kb_path);
		$tpl->tplAssign($this->msg);
		$tpl->tplParse($_GET);
		
		return $tpl->tplPrint(1);
	}
	
	
	function parseLogin(&$tpl, $manager) {
		
		if($manager->is_registered) {
            $auth = &new AuthPriv();
			$tpl->tplAssign('username', $auth->getUsername());
			$tpl->tplAssign('logout_link', $this->_getLink('logout'));
			$tpl->tplAssign('username_link', $this->_getLink('member'));
			$tpl->tplAssign('delim', '|');	
			
			if($auth->getCookie()) {
				$this->msg['logout_msg'] = ''; 
				$tpl->tplAssign('delim', '');	
			}
			
			$tpl->tplSetNeeded('/logged');
		
		
		} elseif($manager->use_registration) {
			
			// should check more to redirect correct after login 
			$tpl->tplAssign('login_link', $this->_getLink('login', $this->category_id, $this->entry_id, '_' . $this->view_id));	
			
			if($manager->getSetting('register_policy')) {
				$tpl->tplAssign('register_link', $this->_getLink('register'));
				$tpl->tplSetNeeded('/register_link');
			}
			
			$tpl->tplSetNeeded('/login_link');
		}
	}	
	
	
	function _getFormatedNavigation($arr, $article_name = false) {		
		
		// skip category generate on some vies or if no categories (one only)	
		if($this->category_nav_generate && $this->display_categories) {
			$arr = TreeHelperUtil::getParentsById($arr, $this->category_id, 'name');
			$arr = &$this->stripVars($arr);
		} else {
			$arr = array();
			if($this->category_id) { $this->home_link = true; }
		}
					
		$view = 'index';
		$arr1 = array();
		if($arr || $this->home_link || $this->view_id == 'files') {
			$str = '<a href="%s">%s</a>';
			$arr1[] = sprintf($str, $this->_getLink(), $this->controller->getSetting('nav_title'));
			
			if($this->view_id == 'files') {
				$view = 'files';
				if($this->category_id || $this->msg_id == 'search') {
					$arr1[] = sprintf($str, $this->_getLink('files'), $this->msg['file_title_msg']);
				} else {
					$arr1[] = $this->msg['file_title_msg'];
				}
			}
			
		} else {
			$arr1[] = $this->controller->getSetting('nav_title');
		}
		
		
		// add article title if have it
		if($article_name !== false) {
			$article_name = (is_array($article_name)) ? $article_name : array($article_name);
			foreach($article_name as $k => $v) { $arr[$k] = $v; } 			
		}
		
		
		$num = count($arr); 
		$i = 1;
		foreach($arr as $k => $v) {
			if($num != $i) {
				$k = (is_numeric($k)) ? $this->_getLink($view, $k, false) : $k;
				$arr1[] = sprintf('<a href="%s">%s</a>',$k, $v);
			} else {
				$arr1[] = sprintf('%s', $v);
			}
			
			$i++;
		}
		
		return implode($this->nav_delim, $arr1);
	}	
	
	
	function _getCategorySelect($manager) {
		$range = &$manager->getCategorySelectRange($manager->categories, $this->top_parent_id);
		$range = $this->stripVars($range);
		
		$select = new FormSelect();
		$select->select_tag = false;
		$select->setSelectWidth(200);
		$select->setRange($range, array(0 => '____'));
		
		return $select->select($this->category_id);
	}

 	function _getCategoryTree($manager) {
		$range = &$manager->getCategoryTreeRange($manager->categories, $this->top_parent_id);
		//$range = $this->stripVars($range);
        $tree_path = APP_CLIENT_PATH . 'client/jscript/dtree/';
		$Tree = '<link rel="stylesheet" href="'. $tree_path . 'dtree.css" type="text/css" />
<script src="'. $tree_path . 'dtree.js"></script>
<script language="JavaScript" type="text/javascript">
var img_path  = "'. $tree_path . '";
var basehref = "'. APP_CLIENT_PATH . '"; ';
        
        foreach($range as $id => $line) {
            if($id==0) {
                $line = sprintf($line, $this->controller->getSetting('nav_title'));
            }
            $Tree .= $line . ' ';
        }
        $Tree .= 'document.write(a);';
        $position = 0;
        if($this->category_id) {
            $position = $this->category_id;
        }
        $Tree .= 'a.openTo(' . $position . ', true);</script>';
		return $Tree;
	}
}
?>